import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";
import { useUserStore } from "../store/modules/user";
import tabRoutes from "./tab";

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login", // 添加默认重定向
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/LoginView.vue"),
    meta: { requiresGuest: true },
  },
  {
    path: "/main",
    name: "Main",
    component: () => import("../views/main/MainView.vue"),
    meta: { requiresAuth: true },
    children: tabRoutes,
  },
  // 添加其他路由...
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 导航守卫
router.beforeEach((to, from) => {
  const userStore = useUserStore();
  const isAuthenticated = userStore.isAuthenticated;

  console.group(`路由导航: ${from.path} → ${to.path}`);
  console.log("需要认证:", to.meta.requiresAuth);
  console.log("需要访客:", to.meta.requiresGuest);
  console.log("已认证:", isAuthenticated);

  // 需要认证但未登录 → 重定向到登录页
  if (to.meta.requiresAuth && !isAuthenticated) {
    console.log("重定向原因: 需要认证但未登录");
    return "/login";
  }

  // 禁止已登录用户访问访客页面 → 重定向到首页
  if (to.meta.requiresGuest && isAuthenticated) {
    console.log("重定向原因: 已登录用户访问访客页面");
    return "/main";
  }

  console.log("允许访问");
  console.groupEnd();

  return true;
});

export default router;
